import pymysql
import sys
import pandas as pd

class logAndRegister:
    def __init__(self):
        self.sql_connect()

    def sql_connect(self):
        self.user_db = pymysql.connect(host='127.0.0.1', # 连接名称，默认127.0.0.1
        user ='root',   # 用户名
        passwd='s159632487',    # 密码
        port= 3306,     # 端口，默认为3306
        db='chujianquant',  # 数据库名称
        charset='utf8')     # 字符编码)
        cursor = self.user_db.cursor()
        sql = "SELECT * FROM users"
        try:
            cursor.execute(sql)
            self.results = cursor.fetchall()
            print(self.results)  #后期改成读入成功
            cursor.close()
        except:
            print("error:unable to fetch from the mysql")

    def register(self):
        name = input("please enter the name you want>>")
        pwd = input("please enter the password>>")
        repwd = input("please enter the same password>>")
        if repwd==pwd:
            for users in self.results:
                if name == users[1]:
                    print("the name has been registered")
                    self.register()
            num = len(self.results)
            sql = "INSERT INTO users (users_id,users_name,users_password) VALUES (%d, '%s', '%s')" % (num, name, pwd)
            cursor = self.user_db.cursor()
            try:
                cursor.execute(sql)
                self.user_db.commit()
                print("register success")
                cursor.close()
            except:
                print("error:write failed")
                self.user_db.rollback()
        else:
            print("error:you have entered different passwords")

    def log_in(self):
        name = input("name >>")
        pwd = input("password >>")
        status = 0
        for users in self.results:
            if name == users[1]:
                status = 1
                if pwd == users[2]:
                    print("log in success")
                else:
                    print("the password is wrong, please input the right answer!")
                    self.log_in()
        if status == 0:
            print("there is no such user,do you want to register?(yes/no)>>")
            temp = input(">>")
            if temp == 'yes':
                self.register()
            elif temp == 'no':
                sys.exit(0)








